<?php
namespace api\modules\v1\controllers;

use api\models\Book;
use api\models\BookChapter;
use common\models\Selector;
use Yii;
use yii\helpers\ArrayHelper;
use yii\rest\Controller;
use yii\web\NotFoundHttpException;

class BookController extends Controller
{
    public function init(){
        Book::setDescLength(70);
    }
    public function actionIndex($sex = 1){
        $rs =  [
            'banner' => Book::randomBook(4),
            'recommend' => Book::randomBook(6),
            'hot' => Book::randomBook(3),
            'done' => Book::randomBook(6),
        ];
        return ['code' => 1,'data' => $rs];
    }

    public function actionInfo($id){
        $bookInfo = Book::findById($id)->attributes;
        $latestChapters = BookChapter::find()->where(['book_id' => $id])->select(['bid','latest_chapters'])->asArray()->one();

        if($latestChapters){
            $bookInfo['bid'] = $latestChapters['bid'];
            $latestChapters = json_decode($latestChapters['latest_chapters'],true);
            ArrayHelper::multisort($latestChapters,'chapter_id',SORT_DESC);
            $latestChapters = array_slice($latestChapters,0,5);
        }

        $rs =  [
            'book' => $bookInfo,
            'chapters' => $latestChapters,
            'recommend' => Book::randomBook(6)
        ];
        return ['code' => 1,'data' => $rs];
    }

    public function actionChapters($id,$sort = 'asc',$p = 1,$ps = 30){
        $chapters = BookChapter::find()->where(['book_id' => $id])->select(['chapters','book_id','bid'])->asArray()->one();
        if($chapters){
            $chapters['chapters'] = json_decode($chapters['chapters'],true);
//            $totalCount = count($chapters['chapters']);
            $sort = strtolower($sort) == 'asc' ? SORT_ASC : SORT_DESC;
            ArrayHelper::multisort($chapters['chapters'],'chapter_id',$sort);

            $chapters['chapters'] = array_slice($chapters['chapters'],($p - 1) * $ps,$ps);
        }

        if(isset($chapters['chapters']) && !empty($chapters['chapters'])){
            return ['code' => 1,'data' => $chapters];
        }
        return ['code' => 0,'msg' => '没有更多章节了。'];
    }


    public function actionBanner($sex = 1){
        return ['code' => 1,'data' => Book::randomBook(4)];
    }

    public function actionRecommend($sex = 1,$p = 1,$ps = 10){
        return ['code' => 1,'data' => Book::randomBook($ps)];
    }

    public function actionHot($sex = 1,$p = 1,$ps = 10){
        return ['code' => 1,'data' => Book::randomBook($ps)];
    }

    public function actionDone($sex = 1,$p = 1,$ps = 10){
        return ['code' => 1,'data' => Book::randomBook($ps)];
    }

    public function actionCategories(){
        $cate =  [
            ['id' => 1,'value' => '武侠仙侠'],
            ['id' => 2,'value' => '都市言情'],
            ['id' => 3,'value' => '玄幻奇幻'],
            ['id' => 4,'value' => '网游竞技'],
            ['id' => 5,'value' => '女生频道'],
            ['id' => 6,'value' => '历史军事'],
            ['id' => 7,'value' => '科幻灵异'],
        ];

        return ['code' => 1, 'data' => $cate];
    }

    public function actionCategoryBook($sex = 1,$p = 1,$ps = 10){
        return ['code' => 1,'data' => Book::randomBook($ps)];
    }

    public function actionBookshelf($p = 1,$ps = 20){
        return ['code' => 1,'data' => Book::randomBook($ps)];
    }

    public function actionHotSearch(){
        $rs =  ['圣墟','大主宰','完美世界','斗破苍穹','神墓'];
        return ['code' => 1,'data' => $rs];
    }

    public function actionSearch($key,$p = 1,$ps = 10){
        return ['code' => 1,'data' => Book::randomBook($ps)];
    }

    public function actionAddBookshelf($id){
        return ['code' => 1];
    }

    public function actionChapterContent($bid,$chapter = 0,$id){

        $url = "https://www.qu.la/book/{$bid}/{$chapter}.html";
        $content = $this->getChapterContent($url);

        return ['code' => 0, 'data' => [
            'title' => 'fuck you',
            'content' => $content,
        ]];
    }

    private function getChapterContent($url){
        $content = '';
        $htmlString = $this->httpGet($url);

        $starIndex = stripos($htmlString,'id="content"');
        $endIndex = stripos($htmlString,'Ps:书友们');

        if(!$endIndex){
            $endIndex = stripos($htmlString,'chaptererror') - 8;
        }

        $content = substr($htmlString,$starIndex  + 13,$endIndex - $starIndex - 13);
        return $content;
    }

    private function httpGet($url){
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "$url",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_HTTPHEADER => array(
                "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
                "Accept-Encoding:gzip, deflate, br",
                "Accept-Language:zh-CN,zh;q=0.9",
                "Cache-Control:max-age=0",
                "Connection:keep-alive",
                "Host:www.qu.la",
                "Upgrade-Insecure-Requests:1",
                "User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36",
            ),
            CURLOPT_REFERER => 'https://www.qu.la',
            CURLOPT_AUTOREFERER => true,
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        return $err ? '' : $response;
    }

}

